﻿using BCCommon;
using BCEntity.OA.BusinessFlowModel.BusinessFlowModel;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.BusinessFlowModel.BusinessFlowModel
{
    /// <summary>
    /// OA系统业务流模型
    /// </summary>
	public class BusinessFlowModelData : IBusinessFlowModelData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_BusinessFlowModel";
        private const string QUERY = @"SELECT BusinessFlowModelId,BusinessFlowModelName,BusinessFlowModelCode,BusinessFlowCategoryId,BusinessFlowCategoryName,CompanyId,CompanyName,TotalStep,
                                            CurrentlyStep,CreateTime,IsGroupBusiness,AllowDelete,BusinessTaskLevel
                                        FROM OA_BusinessFlowModel";
        public BusinessFlowModelData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<bool> Exists(long businessFlowModelId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelId=?BusinessFlowModelId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelId", businessFlowModelId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string businessFlowModelCode)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelCode=?BusinessFlowModelCode", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", businessFlowModelCode, DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<BusinessFlowModelEntity> Add(BusinessFlowModelEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_BusinessFlowModel", new string[] { "BusinessFlowModelName", "BusinessFlowModelCode", "CompanyId", "CompanyName", "TotalStep",
                "CurrentlyStep", "IsGroupBusiness","AllowDelete","BusinessFlowCategoryId","BusinessFlowCategoryName","BusinessTaskLevel" });
            sql = string.Format("{0} {1} WHERE BusinessFlowModelId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelName", entity.BusinessFlowModelName, DbType.AnsiString, size: 20);
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode, DbType.AnsiString, size: 50);
            parameters.Add("?BusinessFlowCategoryId", entity.BusinessFlowCategoryId, DbType.Int32, size: 11);
            parameters.Add("?BusinessFlowCategoryName", entity.BusinessFlowCategoryName, DbType.AnsiString, size: 30);
            parameters.Add("?BusinessTaskLevel", entity.BusinessTaskLevel.ToString(), DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CompanyName", entity.CompanyName, DbType.AnsiString, size: 50);
            parameters.Add("?TotalStep", entity.TotalStep, DbType.Int32, size: 11);
            parameters.Add("?CurrentlyStep", entity.CurrentlyStep, DbType.Int32, size: 11);
            parameters.Add("?IsGroupBusiness", entity.IsGroupBusiness, DbType.Boolean);
            parameters.Add("?AllowDelete", entity.AllowDelete, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowModelEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<BusinessFlowModelEntity> Update(BusinessFlowModelEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_BusinessFlowModel", new string[] { "BusinessFlowModelName", "BusinessFlowModelCode", "CompanyId", "CompanyName", "TotalStep",
                "CurrentlyStep", "IsGroupBusiness","BusinessFlowCategoryId","BusinessFlowCategoryName" ,"BusinessTaskLevel"}, new string[] { "BusinessFlowModelId" });
            sql = string.Format("{0} {1} WHERE BusinessFlowModelId=?BusinessFlowModelId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelId", entity.BusinessFlowModelId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowModelName", entity.BusinessFlowModelName, DbType.AnsiString, size: 20);
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode, DbType.AnsiString, size: 50);
            parameters.Add("?BusinessFlowCategoryId", entity.BusinessFlowCategoryId, DbType.Int32, size: 11);
            parameters.Add("?BusinessFlowCategoryName", entity.BusinessFlowCategoryName, DbType.AnsiString, size: 30);
            parameters.Add("?BusinessTaskLevel", entity.BusinessTaskLevel.ToString(), DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CompanyName", entity.CompanyName, DbType.AnsiString, size: 50);
            parameters.Add("?TotalStep", entity.TotalStep, DbType.Int32, size: 11);
            parameters.Add("?CurrentlyStep", entity.CurrentlyStep, DbType.Int32, size: 11);
            parameters.Add("?IsGroupBusiness", entity.IsGroupBusiness, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowModelEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long businessFlowModelId)
        {
            string sql = @"DELETE FROM OA_BusinessFlowModel WHERE BusinessFlowModelId=?BusinessFlowModelId AND AllowDelete=1";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelId", businessFlowModelId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<BusinessFlowModelEntity> GetEntity(long businessFlowModelId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelId=?BusinessFlowModelId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelId", businessFlowModelId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowModelEntity>(sql, parameters);
        }

        public async Task<BusinessFlowModelEntity> GetEntity(string businessFlowModelCode)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelCode=?BusinessFlowModelCode", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", businessFlowModelCode, DbType.AnsiString, size: 50);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowModelEntity>(sql, parameters);
        }

        public async Task<IEnumerable<BusinessFlowModelEntity>> GetList(int companyId)
        {
            string sql = string.Format("{0} WHERE CompanyId=?CompanyId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyId", companyId, DbType.Int32);
            return await this.databaseContext.Slave.QueryAsync<BusinessFlowModelEntity>(sql, parameters);
        }

        public async Task<(IEnumerable<BusinessFlowModelEntity>, int)> Query(int companyId,string businessFlowModelName, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            wheres.Add("CompanyId=?CompanyId");
            parameters.Add("?CompanyId", companyId, DbType.Int32);
            if (!string.IsNullOrWhiteSpace(businessFlowModelName))
            {
                wheres.Add("BusinessFlowModelName LIKE CONCAT('%',CONCAT(?BusinessFlowModelName,'%'))");
                parameters.Add("?BusinessFlowModelName", businessFlowModelName, DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM OA_BusinessFlowModel {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryPageableListAsync<BusinessFlowModelEntity>(sql, parameters);
        }
    }
}
